package com.shuangyu.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuangyu.common.BaseContext;
import com.shuangyu.common.R;
import com.shuangyu.entity.*;
import com.shuangyu.mapper.OrderMapper;
import com.shuangyu.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    public void submit(Orders orders) {

        long userId = BaseContext.getCurrentId();
        AtomicInteger amount = new AtomicInteger(0);//计算总价格
        long OrderId = IdWorker.getId();//设置订单号

        //获取购物车信息
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);

        //获取用户信息
        User user = userService.getById(userId);

        //获取地址信息
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        //创建订单明细表
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();

            orderDetail.setOrderId(OrderId);//设置订单号
            orderDetail.setAmount(item.getAmount());//设置金额
            orderDetail.setName(item.getName());//设置菜品名称
            orderDetail.setImage(item.getImage());//设置菜品图片
            orderDetail.setDishId(item.getDishId());//设置菜品id
            orderDetail.setSetmealId(item.getSetmealId());//设置套餐id
            orderDetail.setDishFlavor(item.getDishFlavor());//色泽菜品口味
            orderDetail.setNumber(item.getNumber());//设置菜品的数量

            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        //创建订单
        orders.setNumber(String.valueOf(OrderId));//订单号
        orders.setUserId(userId);//下单用户
        orders.setStatus(2);//订单状态码
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//支付时间
        orders.setAddressBookId(orders.getAddressBookId());//地址id
        orders.setAmount(new BigDecimal(amount.get()));//实收金额
        orders.setRemark(orders.getRemark());//备注
        orders.setPhone(addressBook.getPhone());//收货人手机号
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setUserName(user.getName());//用户名称
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );//详细地址

        //创建订单
        this.save(orders);

        //创建订单详细
        orderDetailService.saveBatch(orderDetailList);

        //删除购物车
        LambdaQueryWrapper<ShoppingCart> shoppingCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        shoppingCartLambdaQueryWrapper.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(shoppingCartLambdaQueryWrapper);

    }
}
